/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * dlgRegistrarUsuario.java
 *
 * Created on Oct 18, 2011, 10:53:21 PM
 */

package visual.Seguridad;

import bentity.bePerfil;
import bentity.beUsuario;
import blogic.blLog;
import blogic.blPerfil;
import blogic.blUsuario;
import java.util.ArrayList;
import java.util.Arrays;
import javax.swing.text.*;


/**
 *
 * @author renzo
 */
public class dlgRegistrarUsuario extends javax.swing.JDialog {
    private beUsuario usuario = null;
    
    /** Creates new form dlgRegistrarUsuario */
    public dlgRegistrarUsuario(java.awt.Frame parent, boolean modal, beUsuario usuario) {
        super(parent, modal);
        initComponents();
        this.usuario = usuario;
        this.txtNombre.setDocument(new JTextFieldLimit(15));
        this.txtCargo.setDocument(new JTextFieldLimit(25));
        this.jPasswordField1.setDocument(new JTextFieldLimit(8));
        this.jPasswordField2.setDocument(new JTextFieldLimit(8));
        this.setModal(true);
        visualHelper.centrarDialogoEnPantalla(this);

        //Llenar combo de PErfil
        try{
            blPerfil gestorPerfiles = new blPerfil();
            ArrayList<bePerfil> listaPerfiles = new ArrayList<bePerfil>();
            listaPerfiles = gestorPerfiles.queryAll();

            this.cboPerfil.addItem("");
            for (int i=0; i<listaPerfiles.size(); i++){
                this.cboPerfil.addItem(listaPerfiles.get(i).getDescripcion());
            }

        }
        catch (Exception e){
            e.printStackTrace();
            System.out.print(e.getMessage());
            visualHelper.mostrarMensajeError("Ocurrió un error en la búsqueda de Perfil");
        }

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lblTitulo = new javax.swing.JLabel();
        btnRegistrar = new javax.swing.JButton();
        btnLimpiar = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();
        lblCargo = new javax.swing.JLabel();
        txtCargo = new javax.swing.JTextField();
        lblNombre = new javax.swing.JLabel();
        txtNombre = new javax.swing.JTextField();
        lblContrasenha = new javax.swing.JLabel();
        jPasswordField1 = new javax.swing.JPasswordField();
        cboPerfil = new javax.swing.JComboBox();
        lblPerfil = new javax.swing.JLabel();
        lblReescribeContrasenha = new javax.swing.JLabel();
        jPasswordField2 = new javax.swing.JPasswordField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Thor Store - Registrar usuario");
        setAlwaysOnTop(true);
        setMinimumSize(new java.awt.Dimension(500, 470));
        setModal(true);
        setResizable(false);
        getContentPane().setLayout(null);

        lblTitulo.setFont(new java.awt.Font("Dialog", 0, 36));
        lblTitulo.setForeground(new java.awt.Color(0, 0, 0));
        lblTitulo.setText("Registrar usuario");
        getContentPane().add(lblTitulo);
        lblTitulo.setBounds(100, 20, 320, 43);

        btnRegistrar.setBackground(new java.awt.Color(240, 235, 226));
        btnRegistrar.setFont(new java.awt.Font("Dialog", 0, 12));
        btnRegistrar.setForeground(new java.awt.Color(0, 0, 0));
        btnRegistrar.setText("Registrar");
        btnRegistrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRegistrarActionPerformed(evt);
            }
        });
        getContentPane().add(btnRegistrar);
        btnRegistrar.setBounds(60, 360, 110, 27);

        btnLimpiar.setBackground(new java.awt.Color(240, 235, 226));
        btnLimpiar.setFont(new java.awt.Font("Dialog", 0, 12));
        btnLimpiar.setForeground(new java.awt.Color(0, 0, 0));
        btnLimpiar.setText("Limpiar");
        btnLimpiar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLimpiarActionPerformed(evt);
            }
        });
        getContentPane().add(btnLimpiar);
        btnLimpiar.setBounds(210, 360, 110, 27);

        btnCancelar.setBackground(new java.awt.Color(240, 235, 226));
        btnCancelar.setFont(new java.awt.Font("Dialog", 0, 12));
        btnCancelar.setForeground(new java.awt.Color(0, 0, 0));
        btnCancelar.setText("Cancelar");
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });
        getContentPane().add(btnCancelar);
        btnCancelar.setBounds(360, 360, 110, 27);

        lblCargo.setFont(new java.awt.Font("Dialog", 0, 12));
        lblCargo.setForeground(new java.awt.Color(0, 0, 0));
        lblCargo.setText("Cargo");
        getContentPane().add(lblCargo);
        lblCargo.setBounds(50, 160, 50, 15);

        txtCargo.setFont(new java.awt.Font("Dialog", 0, 12));
        txtCargo.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtCargoKeyTyped(evt);
            }
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtCargoKeyPressed(evt);
            }
        });
        getContentPane().add(txtCargo);
        txtCargo.setBounds(140, 160, 320, 25);

        lblNombre.setFont(new java.awt.Font("Dialog", 0, 12));
        lblNombre.setForeground(new java.awt.Color(0, 0, 0));
        lblNombre.setText("Nombre");
        getContentPane().add(lblNombre);
        lblNombre.setBounds(50, 120, 50, 15);

        txtNombre.setFont(new java.awt.Font("Dialog", 0, 12));
        txtNombre.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtNombreActionPerformed(evt);
            }
        });
        txtNombre.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtNombreKeyTyped(evt);
            }
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtNombreKeyPressed(evt);
            }
        });
        getContentPane().add(txtNombre);
        txtNombre.setBounds(140, 120, 320, 25);

        lblContrasenha.setFont(new java.awt.Font("Dialog", 0, 12));
        lblContrasenha.setForeground(new java.awt.Color(0, 0, 0));
        lblContrasenha.setText("Contraseña");
        getContentPane().add(lblContrasenha);
        lblContrasenha.setBounds(110, 260, 80, 15);

        jPasswordField1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                jPasswordField1KeyTyped(evt);
            }
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jPasswordField1KeyPressed(evt);
            }
        });
        getContentPane().add(jPasswordField1);
        jPasswordField1.setBounds(280, 260, 115, 28);

        cboPerfil.setFont(new java.awt.Font("Dialog", 0, 12));
        getContentPane().add(cboPerfil);
        cboPerfil.setBounds(140, 200, 320, 25);

        lblPerfil.setFont(new java.awt.Font("Dialog", 0, 12));
        lblPerfil.setForeground(new java.awt.Color(0, 0, 0));
        lblPerfil.setText("Perfil");
        getContentPane().add(lblPerfil);
        lblPerfil.setBounds(50, 200, 31, 15);

        lblReescribeContrasenha.setFont(new java.awt.Font("Dialog", 0, 12));
        lblReescribeContrasenha.setForeground(new java.awt.Color(0, 0, 0));
        lblReescribeContrasenha.setText("Reescribir contraseña");
        getContentPane().add(lblReescribeContrasenha);
        lblReescribeContrasenha.setBounds(110, 300, 150, 15);

        jPasswordField2.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                jPasswordField2KeyTyped(evt);
            }
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jPasswordField2KeyPressed(evt);
            }
        });
        getContentPane().add(jPasswordField2);
        jPasswordField2.setBounds(280, 300, 115, 28);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnRegistrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRegistrarActionPerformed
        String strNombre = "";
        String strCargo = "";
        String strPerfil = "";
        String strContrasenhaEncrip = "";
        String strContrasenha = "";
        blUsuario gestorUsuarios = new blUsuario();
        blPerfil gestorPerfiles = new blPerfil();
        bePerfil perfil = new bePerfil();
        encriptado encriptador = new encriptado();

        try{
            //Se valida los campos nombre y cargo
            if (this.txtNombre.getText().equals("")){
                visualHelper.mostrarMensajeError("Debe de llenar el campo Nombre.");
                return;
            }

            if (gestorUsuarios.queryByNombre(this.txtNombre.getText())!=null){
                visualHelper.mostrarMensajeError("El usuario ingresado ya existe.");
                return;
            }

            if (this.txtCargo.getText().equals("")){
                visualHelper.mostrarMensajeError("Debe de llenar el campo Cargo.");
                return;
            }

            if (this.cboPerfil.getSelectedIndex()==0){
                visualHelper.mostrarMensajeError("Debe seleccionar un perfil.");
                return;
            }

            if (this.jPasswordField2.getPassword().length==0 || this.jPasswordField1.getPassword().length==0){
                visualHelper.mostrarMensajeError("Debe llenar el campo Constraseña.");
                return;
            }

            if (this.jPasswordField1.getPassword().length<5 ||
                this.jPasswordField2.getPassword().length<5){
                visualHelper.mostrarMensajeError("La contraseña ingresada debe tener como mínimo 5 caracteres,");
                this.jPasswordField1.setText("");
                this.jPasswordField2.setText("");
                return;
            }

            if (!(Arrays.equals(this.jPasswordField2.getPassword(),this.jPasswordField1.getPassword()))){
                visualHelper.mostrarMensajeError("Las contraseñas ingresadas deben ser iguales.");
                this.jPasswordField1.setText("");
                this.jPasswordField2.setText("");
                return;
            } 

            strNombre = this.txtNombre.getText();
            strCargo = this.txtCargo.getText();
            strPerfil = this.cboPerfil.getSelectedItem().toString();
            strContrasenha = this.jPasswordField1.getText();
                        
            strContrasenhaEncrip = encriptador.encriptar(strContrasenha);

            perfil = gestorPerfiles.queryByNombre(strPerfil);
            beUsuario usuario = new beUsuario(-1, strCargo, strNombre, strContrasenhaEncrip, beUsuario.U_ACTIVO, perfil.getId(),false);
            gestorUsuarios = new blUsuario();
            gestorUsuarios.registrar(usuario);
            visualHelper.mostrarMensajeSatisfaccion("Se registró satisfactoriamente el usuario");
            usuario = gestorUsuarios.queryByNombre(strNombre);
            (new blLog()).registrarLog(this.usuario.getIdUsuario(), this.usuario.getCargo(), "Se registró el usuario: "+usuario.getIdUsuario()+" - "+usuario.getNombre());
            this.limpiarCampos();            
            this.dispose();
        }
        catch (Exception e){
            e.printStackTrace();
            visualHelper.mostrarMensajeError("No se pudo registrar el cliente.");
        }
}//GEN-LAST:event_btnRegistrarActionPerformed

    private void btnLimpiarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLimpiarActionPerformed
        // TODO add your handling code here:
        this.limpiarCampos();
    }//GEN-LAST:event_btnLimpiarActionPerformed

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        // TODO add your handling code here:
        this.setVisible(false);
        this.dispose();
}//GEN-LAST:event_btnCancelarActionPerformed


    private void txtNombreActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtNombreActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtNombreActionPerformed

    private void txtNombreKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtNombreKeyTyped
        // TODO add your handling code here:
        visualHelper.soloTextoyNumeros(evt);
    }//GEN-LAST:event_txtNombreKeyTyped

    private void txtCargoKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtCargoKeyTyped
        // TODO add your handling code here:
        visualHelper.soloNombres(evt);
    }//GEN-LAST:event_txtCargoKeyTyped

    private void jPasswordField1KeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jPasswordField1KeyTyped
        // TODO add your handling code here:
        visualHelper.soloTextoyNumeros(evt);
    }//GEN-LAST:event_jPasswordField1KeyTyped

    private void jPasswordField2KeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jPasswordField2KeyTyped
        // TODO add your handling code here:
        visualHelper.soloTextoyNumeros(evt);
    }//GEN-LAST:event_jPasswordField2KeyTyped

    private void txtNombreKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtNombreKeyPressed
        // TODO add your handling code here:        
        visualHelper.deshabilitaCtrlV(evt);
    }//GEN-LAST:event_txtNombreKeyPressed

    private void txtCargoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtCargoKeyPressed
        // TODO add your handling code here:
        visualHelper.deshabilitaCtrlV(evt);
    }//GEN-LAST:event_txtCargoKeyPressed

    private void jPasswordField1KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jPasswordField1KeyPressed
        // TODO add your handling code here:
        visualHelper.deshabilitaCtrlV(evt);
    }//GEN-LAST:event_jPasswordField1KeyPressed

    private void jPasswordField2KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jPasswordField2KeyPressed
        // TODO add your handling code here:
        visualHelper.deshabilitaCtrlV(evt);
    }//GEN-LAST:event_jPasswordField2KeyPressed

    public void limpiarCampos(){
        this.txtNombre.setText("");
        this.txtCargo.setText("");
        this.jPasswordField1.setText("");
        this.jPasswordField2.setText("");
        this.cboPerfil.setSelectedIndex(0);
    }


    public class JTextFieldLimit extends PlainDocument {
          private int limit;
          // optional uppercase conversion
          private boolean toUppercase = false;

          JTextFieldLimit(int limit) {
           super();
           this.limit = limit;
           }

          JTextFieldLimit(int limit, boolean upper) {
           super();
           this.limit = limit;
           toUppercase = upper;
           }

          public void insertString
            (int offset, String  str, AttributeSet attr)
              throws BadLocationException {
           if (str == null) return;

           if ((getLength() + str.length()) <= limit) {
             if (toUppercase) str = str.toUpperCase();
             super.insertString(offset, str, attr);
             }
           }
    }
  

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnLimpiar;
    private javax.swing.JButton btnRegistrar;
    private javax.swing.JComboBox cboPerfil;
    private javax.swing.JPasswordField jPasswordField1;
    private javax.swing.JPasswordField jPasswordField2;
    private javax.swing.JLabel lblCargo;
    private javax.swing.JLabel lblContrasenha;
    private javax.swing.JLabel lblNombre;
    private javax.swing.JLabel lblPerfil;
    private javax.swing.JLabel lblReescribeContrasenha;
    private javax.swing.JLabel lblTitulo;
    private javax.swing.JTextField txtCargo;
    private javax.swing.JTextField txtNombre;
    // End of variables declaration//GEN-END:variables

}
